use fast_common::models::role::{Role, RoleVo};

use anyhow::{anyhow, Ok, Result};
use fast_common::common::orm_config::RB;
use fast_common::models::user_role::{DefaultRole, UserRole};
use rbatis::crud::CRUD;
use rbatis::db::DBExecResult;
use rbatis::{DateTimeNative, Page, PageRequest};
use rbson::Bson;

#[allow(dead_code)]
pub struct RoleService;

//TODO
impl RoleService {
    pub async fn new_role(mut role: Role) -> Result<DBExecResult> {
        let ret = RB
            .fetch::<Role>("select * from role  where role_name  = ?", vec![Bson::String(
                role.clone().role_name.unwrap(),
            )])
            .await;
        if ret.is_ok() {
            return Err(anyhow!("已存在相同角色名称"));
        }

        role.create_time = Some(DateTimeNative::now());
        role.del_flag = Some(1);
        role.state = Some(1);
        let result = RB.save(&role, &[]).await?;
        Ok(result)
    }

    pub async fn update_role(role: Role) -> Result<u64> {
        // let mut role_result = RB.fetch::<Role>("select * from role where role_id = ?", vec![Bson::UInt64(role.role_id.unwrap())]).await?;

        let result = RB.update_by_wrapper(&role, RB.new_wrapper(), &[]).await?;
        Ok(result)
    }

    pub async fn delete_role(role: Role) -> Result<u64> {
        let result = RB.remove_by_column::<Role, u64>("role_id", role.role_id.unwrap()).await?;
        Ok(result)
    }

    pub async fn role_list(role: RoleVo) -> Result<Page<Role>> {
        let wrapper = RB.new_wrapper_table::<Role>();
        let request_page =
            PageRequest::new(role.page_num.unwrap_or(1), role.page_size.unwrap_or(10));

        let result = RB.fetch_page_by_wrapper::<Role>(wrapper, &request_page).await?;
        Ok(result)
    }

    pub async fn _find_role_by_user(user_id: i64) -> Result<Vec<Role>> {
        let sql = "select a.id,a.role_name,a.index_no,a.remark,a.state,a.create_time from role a  left join user_role b on a.id = b.role_id and a.user_id = ?";
        let x = RB.fetch::<Vec<Role>>(sql, vec![Bson::Int64(user_id)]).await?;
        Ok(x)
    }

    pub async fn choose_default_role(default_role: DefaultRole) -> Result<()> {
        let user_role = RB
            .fetch::<UserRole>("select * from user_role where user_id = ? group by user_id", vec![
                Bson::from(default_role.user_id),
            ])
            .await
            .map_err(|_| anyhow!("未找到当前用户"))?;
        if user_role.default_role_id.unwrap() != default_role.default_role_id {
            RB.fetch("update user_role set default_role_id =null  where user_id = ?", vec![
                Bson::from(default_role.user_id),
            ])
            .await?;
            RB.fetch("update user_role set default_role_id = ? where user_id  = ?", vec![
                Bson::from(default_role.default_role_id),
                Bson::from(default_role.user_id),
            ])
            .await?;
            Ok(())
        } else {
            Err(anyhow!("登录用户的角色与当前选择的角色相同！！！"))
        }
    }
}
